<?php

class pollActions extends sfActions {

    public function preExecute() {
        date_default_timezone_set(AppTools::TIMEZONE);
    }

    public function executeList(sfWebRequest $request) {
        $name = $request->getParameter('name', null);
        $this->name = $name;

        $rows = PollQuestionTable::getList($name);
        $this->rows = $rows;
    }

    public function executeDetails(sfWebRequest $request) {
        $id = $request->getParameter('id');
        $pollQuestion = PollQuestionTable::retrieveByPk($id);
        $result = PollQuestionTable::getResults($id);

        $arr = array();
        $total = 0;
        foreach ($result as $i) {
            $arr[] = array('data' => $i['vote_count'], 'label' => "({$i['vote_count']}) " . $i['body']);
            $total += $i['vote_count'];
        }

        $this->pollQuestion = $pollQuestion;
        $this->data = $arr;
        $this->total = $total;
    }

    public function executeUpdate(sfWebRequest $request) {
        $id = $request->getParameter('id');
        $question = trim($request->getParameter('question', ''));
        $answers = $request->getParameter('answers', array());

        if ($id) {
            $pollQuestion = PollQuestionTable::retrieveByPK($id);
            if (!$pollQuestion) {
                $this->getUser()->setFlash('warning', 'Санал асуулга олдсонгүй');
                $this->redirect($request->getReferer());
            }
            if (!count($answers)) {
                $answers = PollAnswerTable::retrieveByPollQuestion($id);
            }
            $flash = 'Амжилттай заслаа';
        } else {
            $pollQuestion = new PollQuestion();
            $pollQuestion['created_at'] = date('Y-m-d H:i:s');
            $flash = 'Амжилттай нэмлээ';
        }


        $answers = AppTools::sortTreeArray($answers);

        if ($request->isMethod('post')) {
            $err = 0;
            if (!$question) {
                $this->getUser()->setFlash('warning', 'Та асуулт оруулна уу.');
                $err = 1;
            }
            if (count($answers) < 2) {
                $this->getUser()->setFlash('warning', 'Та дор хаяж хоёр сонголт оруулна уу.');
                $err = 1;
            }
            if ($err === 0) {
                $pollQuestion['body'] = $question;
                $pollQuestion->save();
                $id = $pollQuestion['id'];

                $paIndices = array();
                foreach ($answers as $answer) {
                    if ($answer['id'] < 0) {
                        $pollAnswer = new PollAnswer();
                    } else {
                        $pollAnswer = PollAnswerTable::retrieveByPk($answer['id']);
                    }

                    if ($answer['parent_id'] >= 0) {
                        $pollAnswer['parent_id'] = $answer['parent_id'];
                    } else {
                        $pollAnswer['parent_id'] = $paIndices[$answer['parent_id']];
                    }
                    $pollAnswer['body'] = $answer['body'];
                    $pollAnswer['poll_question_id'] = $id;
                    $pollAnswer['created_at'] = date('Y-m-d H:i:s');
                    $pollAnswer->save();

                    $paIndices[$answer['id']] = $pollAnswer['id'];
                }

                $this->getUser()->setFlash('success', $flash);
                $this->redirect('@poll_list');
            }
        }

        $question = strlen($question) ? $question : $pollQuestion['body'];

        $this->id = $id;
        $this->question = $question;
        $this->answers = $answers;
    }

    public function executeChangeState(sfWebRequest $request) {
        $pollQuestion = PollQuestionTable::retrieveByPk($request->getParameter('id'));
        if ($pollQuestion) {
            if ($pollQuestion->is_active == PollQuestionTable::ACTIVE) {
                $pollQuestion->setIsActive(PollQuestionTable::PASSIVE);
                $this->getUser()->setFlash('success', 'Амжилттай устгалаа');
            } elseif ($pollQuestion->is_active == PollQuestionTable::PASSIVE) {
                $pollQuestion->setIsActive(PollQuestionTable::ACTIVE);
                $this->getUser()->setFlash('success', 'Амжилттай сэргээлээ');
            }
            $pollQuestion->save();
        } else {
            $this->getUser()->setFlash('error', 'Санал асуулга олдсонгүй!');
        }

        $this->redirect('@poll_list');
    }

    public function executeAnswerDelete(sfWebRequest $request) {
        $id = $request->getParameter('id', 0);
        if ($id) {
            $pollAnswer = PollAnswerTable::retrieveByPk($id);
            $pollAnswer['is_active'] = PollAnswerTable::PASSIVE;
            $pollAnswer->save();
            die('1');
        }
        die('0');
    }

}
